package pv3d
{
	
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	import loaders.AutoRetryLoader;
	
	import memory.MemoryRecovery;
	
	import org.papervision3d.core.proto.MaterialObject3D;
	
	import view.ToolBitmapData;
	/**
	 * 根据所给的地址加载movieClip,并在指定的bitmapMaterial上添加动画
	 */ 
	public class BitmapMaterialAddon extends Sprite
	{
		private var path:String;                //所要添加的图片的路径
		private var _id:String;                  //id
		protected var matritx:Matrix;           //转化图片的矩阵
		private var hasUpdate:Boolean=false;    //是否更新了图片
		protected var target:MaterialObject3D;    //所要添加动画的素材
		protected static var movieCache:Dictionary=new Dictionary();
		private var loader:AutoRetryLoader;     //加载动画
		private var mc:MovieClip;               //指定的要加到材质上的电影
		protected var cache:Array=new Array();  //用来cache图片
		private var currentIndex:int=-1;        //动画的当前帧数
		private var maxIndex:int=-1;            //动画的最大帧数
		private var sourceBitmap:BitmapData;
		public function BitmapMaterialAddon(id:String,target:MaterialObject3D,path:String,property:Object)
		{
			if(target==null || path==null || path=="" || property==null || id==null) return;//不符合条件就不添加动画
			this._id=id;
			this.path=path;
			this.target=target;
			this.initLoader();
			this.initMatritx(property);
		}
		public function get id():String
		{
			return this._id;
		}
		/**
		 * 初始化加载动画的loader
		 */ 
		private var request:URLRequest;
		private function initLoader():void
		{
			loader=new AutoRetryLoader();
			request=new URLRequest(this.path);
			loader.load(request);
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,on_loaded);
		}
		private function on_loaded(e:Event):void
		{
			mc=MovieClip(loader.content);
			currentIndex=mc.currentFrame-1;
			maxIndex=mc.totalFrames;
			if(movieCache[this]==null)          //mc没有被缓存成图片
			{
				movieCache[this]=cache;         //开辟新的空间缓存图片
			}else
			{
				cache=movieCache[this];         //有被缓存过，就使用以前的
			}
			getSourceBitmap();
			loader.dispose();
			start();
		}
		/**
		 * 初始化转换的矩阵
		 */ 
		private function initMatritx(property:Object):void
		{
			if(property==null) return;
			//获取旋转矩阵的数据
			var x:Number=property["x"]?property["x"]:0;
			var y:Number=property["y"]?property["y"]:0;
			var scaleX:Number=property["scaleX"]?property["scaleX"]:1;
			var scaleY:Number=property["scaleY"]?property["scaleY"]:1;
			var rotation:Number=property["rotation"]?property["rotation"]:0;
			//初始化旋转矩阵的数据
			this.matritx=new Matrix();
			this.matritx.rotate(rotation);
			this.matritx.scale(scaleX,scaleY);
			this.matritx.tx=x;
			this.matritx.ty=y;
//			Application.application.addEventListener(MouseEvent.MOUSE_DOWN,function():void
//			{
//				matritx.tx--;
//				trace(matritx.tx+"::"+matritx.ty);
//			});
//			Application.application.addEventListener(MouseEvent.MOUSE_WHEEL,function():void
//			{
//				matritx.ty--;
//				trace(matritx.tx+"::"+matritx.ty);
//			});
		}
		/**
		 * 获取原始的图片，材质被画上动画之后，可以用原始图片复原
		 */ 
		private function getSourceBitmap():void
		{
			this.sourceBitmap=new BitmapData(loader.width*1.2,loader.height);
			sourceBitmap.copyPixels(target.bitmap,new Rectangle(matritx.tx,matritx.ty,loader.width*1.2,loader.height),new Point(0,0));
		}
		/**
		 * 开始更新图片
		 */ 
		public function start():void
		{
			if(!this.hasEventListener(Event.ENTER_FRAME))
			{
				this.addEventListener(Event.ENTER_FRAME,updateBitmap);
			}
		}
		/**
		 * 停止更新图片
		 */ 
		public function stop():void
		{
			if(this.hasEventListener(Event.ENTER_FRAME))
			{
				this.removeEventListener(Event.ENTER_FRAME,updateBitmap);
			}
		}
		/**
		 * 更新图片
		 */ 
		private function updateBitmap(e:Event):void
		{
			if(target==null || target.bitmap==null || sourceBitmap==null)return ;
			currentIndex++;                         //每过一帧，帧数+1
			if(currentIndex>=maxIndex)currentIndex=1;//保持不越界
			target.bitmap.copyPixels(sourceBitmap,new Rectangle(0,0,sourceBitmap.width,sourceBitmap.height),new Point(matritx.tx,matritx.ty));//复原图片
			if(mc!=null && cache.length==mc.totalFrames)//MC的动画全部被缓存了就停止MC
			{
				mc.stop();
				mc=null;
			}
			var bitmap:BitmapData;
			if(cache[currentIndex]==null)//如果动画当前帧，对应的图片没有CACHE，那么就先获取动画当前帧的图片，并Cache
			{
				if(mc!=null) bitmap=ToolBitmapData.getInstance().drawDisplayObject(mc);
				cache[currentIndex] = bitmap;
			}else//如果图片已经被CACHE过
			{
				bitmap=cache[currentIndex];
			}
			if(bitmap!=null) target.bitmap.copyPixels(bitmap,new Rectangle(0,0,sourceBitmap.width,sourceBitmap.height),new Point(matritx.tx,matritx.ty));
		}
		/**
		 * 清除内存
		 */
		public function dispose():void
		{
			//回收事件
			MemoryRecovery.getInstance().gcFun(loader.contentLoaderInfo,Event.COMPLETE,on_loaded);
			MemoryRecovery.getInstance().gcFun(this,Event.ENTER_FRAME,updateBitmap);
			//回收对象
			this.path=null;
			this._id=null;
			this.matritx=null;
			this.target=null;
			this.loader.dispose();
			this.loader=null;
			this.cache=null;
			movieCache[this]=null;
			if(mc!=null)
			{
				mc.stop();
				mc=null;
			}
			sourceBitmap.dispose();
			sourceBitmap=null;
		}
	}
}